import { CydonElement, define } from 'cydon'
import { API } from '../api'
import { error } from '../utils'
import stringToColor from '../utils/colorize'
import { delay } from '@cydon/ui'

type Tag = {
	name: string
	color: string
}

@define('img-classifier')
export class ImgClassifier extends CydonElement {
	name = ''
	timeout = ''
	_colored = true
	get colored() {
		return this._colored
	}
	set colored(value) {
		this._colored = value
		this.fill(this.tags.map(x => x.name).join(' '))
	}
	tags: Tag[] = []

	connectedCallback() {
		// 自动填充上次使用的分类器名称
		this.name = localStorage.getItem('classifier-name') || ''
		addEventListener('unload', () => localStorage.setItem('classifier-name', this.name))
		super.connectedCallback()
		this.addEventListener('file', (e: CustomEvent) => {
			const file = e.detail[0]
			this.classify(file)
		})
	}

	/** 分类图片 */
	classify(file: string) {
		if (!this.name)
			error('请输入分类器名称');
		(this.timeout ? Promise.race([
			delay(+this.timeout),
			API.classifyFile(this.name, file)]) :
			API.classifyFile(this.name, file)).then((r) => {
				if (!r)
					throw new Error('请求超时')
				const tags = r[0]
				if (!tags)
					throw new Error('无法识别的图片，仅支持jpg、png格式')
				this.fill(tags)
			}).catch(error)
	}

	/** 填充标签 */
	fill(tags: string) {
		this.tags = tags.split(' ').map(x => ({
			name: x,
			color: this.colored ? '#' + stringToColor(x) : 'unset'
		}))
	}
}

declare global {
	interface HTMLElementTagNameMap {
		'img-classifier': ImgClassifier
	}
}